<?php

namespace app\branchoffice\model;

use app\admin\model\AuthGroup;
use fast\Tree;
use think\Cache;
use think\Db;
use think\Exception;
use think\Model;

class Department extends Model
{
    // 表名
    protected $name = 'branchoffice_department';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected static $instance;
    /**
     * 初始化
     * @access public
     * @param array $options 参数
     * @return Tree
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }

        return self::$instance;
    }


    protected static function init()
    {

  /* before_write,不管是插入新数据还是修改数据都会执行;
    before_insert,只有插入新数据时才会执行;
    before_update,只有修改数据时才会执行
  */

        self::beforeUpdate(function ($row) {
            if (isset($row['pid'])) {
                $childrenIds = self::getChildrenIds($row['id'], true);
                if (in_array($row['pid'], $childrenIds)) {
                    throw new Exception("上级组织部门不能是其自身或子组织部门");
                }
            }
        });
        self::afterInsert(function ($row) {
            //创建时自动添加权重值
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
          
        });
        self::afterDelete(function ($row) {
            //删除时，删除子节点，同时将所有相关部门成员删除
            $childIds = self::getChildrenIds($row['id'],$row['office_id']);
            if ($childIds) {
                Department::destroy(function ($query) use ($childIds) {
                    $query->where('id', 'in', $childIds);
                });
            }
            $childIds[] = $row['id'];

       //     db('department_admin')->where('department_id', 'in', $childIds)->delete();
          
        });
        self::afterWrite(function ($row){
            $changed = $row->getChangedData();
            //隐藏时判断是否有子节点,有则隐藏
            if (isset($changed['status']) && $changed['status'] == 'hidden') {
                $childIds = self::getChildrenIds($row['id'],$row['office_id']);
                db('department')->where('id', 'in', $childIds)->update(['status' => 'hidden']);
            }
          

        });
    }

    public static function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    /**
     * 获取栏目的所有子节点ID
     * @param int $id 栏目ID
     * @param bool $withself 是否包含自身
     * @return array
     */
    public static function getChildrenIds($id,$office_id, $withself = false)
    {
        static $tree;
        if (!$tree) {
            $tree = \fast\Tree::instance();
            $tree->init(collection(self::order('weigh desc,id desc')->where('office_id',$office_id)->field('id,pid,name,status')->select())->toArray(), 'pid');
        }
        $childIds = $tree->getChildrenIds($id, $withself);
        return $childIds;
    }


    /**
     * 所有部门
     */
    public static function allDepartment($office_id)
    {
        return self::order('weigh DESC,id ASC')->where('office_id',$office_id)->where(['status' => 'normal'])->select();
    }


    /**
     * 获取当前部门归属的最高组织id(最顶级)
     */
    public static function getOrganiseID($departmentid)
    {
        if (!$departmentid) return 0;
        $organise_id = self::where(['id' => $departmentid])->value('organise_id');
        return $organise_id ? $organise_id : $departmentid;//如果没有最高，本身自己就是最高；

    }



}